﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

public class ModelAnimationEvent:MonoBehaviour
{
    public Animator animator;
    public AnimationClipEvent eventData;
    private void Awake()
    {
        if (animator == null||eventData.animatorController == null)
            return;

        animator.gameObject.AddComponent<AnimationEventFunction>();

        var animatorOverideController = new AnimatorOverrideController(eventData.animatorController);
        List<KeyValuePair<AnimationClip, AnimationClip>> list = new List<KeyValuePair<AnimationClip, AnimationClip>>();
        StringBuilder builder = new StringBuilder();
        foreach(var item in eventData.clips)
        {
            list.Add(new KeyValuePair<AnimationClip, AnimationClip>(item.kay,item.value));
            foreach(var data in eventData.eventDatas.Where(x => x.clipName == item.kay.name))
            {
                AnimationEvent animationEvent = new AnimationEvent();
                animationEvent.functionName = data.functionName;
                animationEvent.time = data.time * item.value.length;
                for(int i=0;i<data.parameters.Length;i++)
                {
                    builder.AppendFormat("{0}#{1}~",data.types[i],data.parameters[i]);
                }
                if (builder.Length > 0)
                    builder.Length--;
                animationEvent.stringParameter = builder.ToString();
                item.value.AddEvent(animationEvent);
                builder.Clear();
            }
        }
        animatorOverideController.ApplyOverrides(list);
        animator.runtimeAnimatorController = animatorOverideController;

       
    }
}
